# -*- coding: utf-8 -*-
from flask import Blueprint,render_template,g,request,jsonify
from models.member.Member import Member
from models.member.MemberComments import MemberComments
from models.food.Food import Food
from models.pay.PayOrder import PayOrder
from Service import Pagination,UserService
from sqlalchemy import or_
from app import db,app

route_member = Blueprint('member_page',__name__ )

@route_member.route("/index")
def index():
    current_user = g.current_user
    page_num = int(request.args.get("page", 1))

    # 搜索
    status = int(request.args.get("status", -1))
    search = request.args.get("search", "")
    # 保存搜索状态
    condition = {
        "status": status,
        "search": search
    }

    query = Member.query
    if status > -1 and search == "":
        query = query.filter_by(status=status)
    if status == -1 and search != "":
        query = query.filter(or_(Member.nickname.contains(search), Member.mobile.contains(search)))
    if status > -1 and search != "":
        query = query.filter(Member.status == status, or_(Member.nickname.contains(search), Member.mobile.contains(search)))

    # 分页
    totals = query.count()
    pagination = Pagination(page_num, totals)

    if totals != 0:
        data_list = query.offset(pagination["offset"]).limit(pagination["page_size"]).all()
    else:
        data_list = []
    pagination["data_list"] = data_list
    return render_template("member/index.html",current_user=current_user,pagination=pagination,condition=condition)

@route_member.route("/info")
def info():
    current_user = g.current_user
    id = int(request.args.get("id"))
    member = Member.query.get(id)
    if member is None:
        return render_template("error/error.html")

    order_info_list = db.session.query(PayOrder.order_sn,PayOrder.pay_time,PayOrder.pay_price,PayOrder.status).filter_by(member_id=id).order_by(PayOrder.pay_time.desc()).limit(app.config["ORDER_INFO_SIZE"]).all()

    comments_list = []
    comments = MemberComments.query.filter_by(member_id=id).order_by(MemberComments.created_time.desc()).limit(app.config["COMMENTS_INFO_SIZE"]).all()

    for item in comments:
        comment = dict()
        comment["created_time"] = item.created_time
        comment["food_name"] = Food.query.get(item.food_id).name
        comment["content"] = item.content
        comment["score"] = item.score

        comments_list.append(comment)

    return render_template("member/info.html",current_user=current_user,member=member,order_info_list=order_info_list,comments_list=comments_list)


@route_member.route("/edit",methods=["GET","POST"])
def edit():
    current_user = g.current_user
    if request.method == "GET":
        id = int(request.args.get("id"))
        member = Member.query.get(id)
        if member is None:
            return render_template("error/error.html")
        return render_template("member/edit.html",current_user=current_user,member=member)

    req_dict = request.values
    member = Member.query.get(req_dict["id"])

    if member is None:
        return render_template("error/error.html")

    member.nickname = req_dict["nickname"]

    member.updated_time = UserService.geneTime()

    try:
        db.session.add(member)
        db.session.commit()
    except:
        return jsonify({"code": -1, "msg": "修改失败！"})

    return jsonify({"code": 200, "msg": "修改成功！"})

@route_member.route("/remove",methods=["POST"])
def remove():
    try:
        id = request.form.get("id")
        Member.query.filter_by(id=id).update({"status": 0})
        db.session.commit()
    except:
        return jsonify({"code":-1,"msg":"删除失败！"})

    return jsonify({"code":200,"msg":"删除成功！"})


@route_member.route("/recover",methods=["POST"])
def recover():
    try:
        id = request.form.get("id")
        Member.query.filter_by(id=id).update({"status": 1})
        db.session.commit()
    except:
        return jsonify({"code":-1,"msg":"恢复失败！"})

    return jsonify({"code":200,"msg":"恢复成功！"})


@route_member.route("/comment")
def comment():
    current_user = g.current_user
    page_num = int(request.args.get("page", 1))
    query = MemberComments.query
    totals = query.count()
    pagination = Pagination(page_num, totals)

    comments = []
    if totals != 0:
        data_list = query.offset(pagination["offset"]).limit(pagination["page_size"]).all()
        for item in data_list:
            comment = {}
            member = Member.query.filter_by(id=item.member_id).first()
            comment["member_img"] = member.avatar
            comment["member_nickname"] = member.nickname
            comment["food"] = Food.query.filter_by(id=item.food_id).first().name
            comment["score"] = item.score
            comment["content"] = item.content

            comments.append(comment)
    else:
        data_list = []
    pagination["comments"] = comments

    return render_template("member/comment.html",current_user=current_user,pagination=pagination)
